#include <stdio.h>
#include <stdlib.h>
// #include <string.h>

#include <lib/Log/include/Log.h>
#include <SocketUtils.h>

#include <FinalCType/List.h>
#include <FinalCType/String.h>
#include <Thread.h>

#include <errno.h>

// 记录所有的远程连接
List *origins = NULL;

createThreadHandle(MessageHandler) {

    TcpSocket tcp;
    memcpy(&tcp, ((TcpSocket*)data), sizeof(tcp));
    
    while (1)
    {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(tcp.socket, &fds);

        int ret = select(tcp.socket+1, &fds, NULL, NULL, NULL);

        if (ret > 0) {
            if (FD_ISSET(tcp.socket, &fds)) {
                // char buffer[1000];
                String *buffer = createStringWith_size(1000);

                int len;
                if ((len = tcpSocketRead(&tcp, buffer->value, buffer->len)) == 0) {
                    INFO_LOG("%s", strerror(errno));
                    close(tcp.socket);
                    if (socketConnect(&tcp, &tcp.address, sizeof(tcp.address))) {

                    } else {
                        ERROR_LOG("Socket 已断开连接");
                        // connected = false;
                        continue;
                    }
                    // exit(0);
                }

                INFO_LOG("发现新消息: %s", buffer->value);

                // 新消息
                if (stringContains_cstr(buffer, "msg::::")) {
                    List *iter;
                    // 转发给所有远程连接
                    list_foreach(iter, origins) {
                        INFO_LOG("发现新消息: 转发中");
                        tcpSocketWrite(&tcp, buffer->value, buffer->len);
                    }
                }

                // 新连接
                if (stringContains_cstr(buffer, "connect::::")) {

                    INFO_LOG("发现新用户: %s", buffer->value+11);
                    
                    // UdpSocketOrigin *connect = calloc(1, sizeof(UdpSocketOrigin));
                    // tcpSocketRead(&tcp, buffer->value, buffer->len);
                    origins = listAppend(origins, &tcp);


                    String *message = createStringWith_copy_cstr("msg::::来自服务器::::已收到连接请求.");
                    tcpSocketWrite(&tcp, message->value, message->len);
                    INFO_LOG("发送消息: %s", message->value);

                    // 释放 buffer
                    deleteString(message);
                }

                // 释放 buffer
                deleteString(buffer);
            }
        }
    }
};


int	main(int argc, char **argv) {
    
    INFO_LOG("正在启动服务: 0.0.0.0:%s", argv[1]);
    
    TcpSocketServer tcp = {0};
    if (createTcpSocketServer(&tcp, atoi(argv[1]))) {
        INFO_LOG("启动服务完成.");

        while (1)
        {
            TcpSocket client;
            if (socketAccept(&tcp, &client)) {
                Thread thread;
                createThread(&thread, MessageHandler, &client);
                runThread(&thread);
            }
        }
    }

    return 0;
}